<template>
  <div>
    <ZgDrawer :width="view.width" :title="view.title" v-model="visible">
      <div class=" flx-b">
        <div >
          <span>流程名称：</span><span class="mr10">{{ processObj.processName }}</span><span>流程编号：</span><span>{{ processObj.processCode }}</span>
        </div>

      </div>
      <ZgCondition
        ref="condition"
        :labelCol="6"
        :columnCol="6"
        :showFilterAdminBtn="false"
        :uniqueName="uniqueName"
        :conditions="conditions"
        :showInlineBtn="true"
        :currFilterName="filter&&filter.name?filter.name:''"
        @search="onCondition"
        @refresh="initFilters"
        @height="h=>conditionHeight=h" />

      <a-tabs v-model="activeKey" hide-add type="editable-card" @edit="onDelPane">
        <a-tab-pane v-for="pane in panesArr" :key="pane.key" :tab="pane.title" :closable="pane.closable">
          <div v-if="activeKey === '-1'">
            <a-table
              size="small"
              bordered
              :customHeaderRow="()=>{return { style: { background: '#f2f2f2' } }}"
              :pagination="false"
              :data-source="list"
              :scroll="{ x: 2000, y: 400 }">
              <a-table-column :width="45" title="序号">
                <template slot-scope="text,record,index">
                  <div class="wfull tac">{{ index+1 }}</div>
                </template>
              </a-table-column>
              <a-table-column
                v-for="(column,i) in columns"
                :key="`column${i}`"
                :width="column.width"
                :title="column.label">
                <template slot-scope="record">
                  <ZgDicHolder v-if="column.code==='formType'" parentCode="flowIsConfig" :code="record[column.code]" />
                  <ZgDicHolder v-else-if="column.code==='isSeal'" parentCode="flowIsConfig" :code="record[column.code]" />
                  <ZgDicHolder v-else-if="column.code==='isReturn'" parentCode="flowIsConfig" :code="record[column.code]"></ZgDicHolder>
                  <ZgDicHolder v-else-if="column.code==='isReturned'" parentCode="flowIsConfig" :code="record[column.code]"></ZgDicHolder>
                  <ZgDicHolder v-else-if="column.code==='isEdit'" parentCode="flowIsConfig" :code="record[column.code]"></ZgDicHolder>
                  <ZgDicHolder v-else-if="column.code==='isStepEnd'" parentCode="flowIsConfig" :code="record[column.code]"></ZgDicHolder>
                  <ZgDicHolder v-else-if="column.code==='billStep'" parentCode="flowBillStep" :code="record[column.code]"></ZgDicHolder>
                  <ZgDicHolder v-else-if="column.code==='shortMessage'" parentCode="flowIsConfig" :code="record[column.code]"></ZgDicHolder>
                  <ZgDicHolder v-else-if="column.code==='shortMessageType'" parentCode="flowIsConfig" :code="record[column.code]"></ZgDicHolder>
                  <ZgDicHolder v-else-if="column.code==='isBackApproval'" parentCode="flowIsConfig" :code="record[column.code]"></ZgDicHolder>
                  <ZgDicHolder v-else-if="column.code==='approveType'" parentCode="flowApproveType" :code="record[column.code]"></ZgDicHolder>
                  <ZgDicHolder v-else-if="column.code==='selectHandlerMode'" parentCode="flowHandlerMode" :code="record[column.code]"></ZgDicHolder>
                  <span v-else>{{ record[column.code] }}</span>
                </template>
              </a-table-column>

            </a-table>
          </div>
          <div v-else>

            <a-form :model="pane" :label-col="labelCol" :wrapper-col="wrapperCol">

              <a-row :gutter="24">
                <a-col
                  v-for="(item, index) in pane.inputValue"
                  :key="index"
                  :span="12"
                >
                  <a-form-item :label="item.label" :key="index">
                    <a-input v-model="item.value" />
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
            <a-table
              size="small"
              bordered
              :customHeaderRow="()=>{return { style: { background: '#f2f2f2' } }}"
              :pagination="false"
              :data-source="pane.stepSubVos"
            >

              <a-table-column
                key="stepName"
                width="300"
                title="节点名称">
                <template slot-scope="record">
                  <a-select default-value="lucy" v-model="record.stepNo" style="width: 120px" >
                    <a-select-option :value="v.stepNo" v-for="(v,i) in list" :key="i">
                      {{ v.stepName }}
                    </a-select-option>
                  </a-select>
                </template>
              </a-table-column>
              <a-table-column
                key="stepNo"
                width="300"
                title="节点编号">
                <template slot-scope="record">
                  {{ record.stepNo }}
                </template>
              </a-table-column>
              <a-table-column
                key="nextStepId"
                width="300"
                title="下个环节">
                <template slot-scope="text, record">
                  <ZgInput v-model="record.nextStepId" />
                </template>
              </a-table-column>
              <a-table-column
                key="personList"
                width="300"
                title="环节处理人">
                <template slot-scope="text, record">
                  <a-select
                    mode="multiple"
                    placeholder="请选择处理人"
                    :default-value="record.personList"
                    :maxTagCount="2"
                    maxTagPlaceholder="..."
                    style="width: 200px"
                  >
                    <a-select-option v-for="item in processPerson" :key="item.value">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </template>
              </a-table-column>
              <a-table-column fixed="right" title="操作">
                <template slot-scope="text,record">

                  <div class="flx-s">
                    <a-button
                      class="mr10"
                      type="link"
                      @click="toDel(record)"
                    >
                      <i :class="`fa fa-trash mr5`"/>删除
                    </a-button>
                  </div>
                </template>
              </a-table-column>

            </a-table>
            <div class="mt20 flx-e">
              <ZgButton icon="save" @click="saveProcess(pane.flowCode, pane.key,pane)">保存</ZgButton>
            </div>
          </div>
        </a-tab-pane>
      </a-tabs>
    </ZgDrawer>

  </div>
</template>
<script>

import ZgCondition from '@/comp/api/new/ZgCondition.vue'

export default {
  components: {
    ZgCondition
  },
   props: {
    view: {
      type: Object,
      default: () => {
        return {
          width: '90%',
          title: '流程采集列表页'
        }
      }
    }

  },
  data () {
    return {
      flowId: '',
      visible: false,
      hasInit: true,
      initLoading: false,
      conditionHeight: 70,
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      filter: null,
      filters: [],
      adminWidth: 0,
      uniqueName: '',
      layout: {
        视图边距: 0
      },
      param: null,
      processObj: {
        processName: '',
        processCode: ''
      },
      pageOpt: {
        showSearchBtn: false,
        showRefreshBtn: false,
        showConditionBtn: false,
        showHeaderConfig: false,
        showAttachBtn: false,
        showLayoutMode: false
      },
      columns: [
        { code: 'stepName', label: '环节名称', width: 120, isShow: true },
        { code: 'stepNo', label: '环节编号', width: 120, isShow: true },
        { code: 'formType', label: '是否配置', width: 120, isShow: true },
        { code: 'stepFormName', label: '表单名称', width: 120, isShow: true },
        { code: 'stepHandler', label: '处理人', width: 120, isShow: true },
        { code: 'nextStepId', label: '下一环节', width: 120, isShow: true },
        { code: 'isEdit', label: '可重新编辑', width: 120, isShow: true },
        { code: 'isSeal', label: '是否盖章', width: 120, isShow: true },
        { code: 'isReturn', label: '可以退回', width: 120, isShow: true },
        { code: 'isReturned', label: '可以被退回', width: 120, isShow: true },
        { code: 'approveType', label: '单签会签', width: 120, isShow: true },
        { code: 'isStepEnd', label: '是否结束节点', width: 120, isShow: true },
        { code: 'billStep', label: '环节发票类型', width: 120, isShow: true },
        { code: 'selectHandlerMode', label: '模式', width: 120, isShow: true },
        { code: 'shortMessage', label: '是否需要发送短信', width: 140, isShow: true },
        { code: 'shortMessageType', label: '短信模板类型', width: 120, isShow: true },
        { code: 'isBackApproval', label: '退回是否需要审批', width: 140, isShow: true }
      ],
      conditions: [
        { code: 'stepName', compType: '单行文本', label: '环节名称', defaultVal: '' }

      ],
      batchBtns: [ ],
      dataBtns: [

      ],
      attTypeArr: [
        { name: '附件1', type: '.png', limit: 10 },
        { name: '附件2', type: '.xlsx', limit: 10 }
      ],
      panes: [
        { title: '主流程', content: 'Content of Tab 1', key: '-1' }
      ],
      panesArr: [],
      activeKey: '-1',
      list: [],
      processPerson: [
        { name: '1407994149180936192', value: '张晓波' },
        { name: '1864926877955383297', value: '张晓波' }
      ],
      form: this.$form.createForm(this)
    }
  },
  mounted () {
    // this.initFilters(true)
  },
  methods: {
    // 分支数据保存
    saveProcess (flowCode, key, pane) {
      const form = {
        flowCode: this.processObj.processCode,
        id: pane.id,
        name: pane.name,
        stepSubVos: pane.stepSubVos
      }
      for (let i = 0; i < pane.inputValue.length; i++) {
        form[pane.inputValue[i].key] = pane.inputValue[i].value
      }

      this.$http.post('/zg-autoflow/autoFlow/sub/addOrUpdate', form, data => {
        this.$message.success('编辑成功')
        this.promiseAll(this.param)
      })
    },
    initFilters (changeFilter) {
      // 获取过滤器
      const key = this.currentUser.username + '_diyFilter_' + this.uniqueName
      const result = localStorage.getItem(key)
      if (result) {
        this.filters = JSON.parse(result)
        if (changeFilter) {
          this.filter = this.filters[0]
          this.$refs.condition.set(this.filter.condition)
        }
      } else {
        this.filters = []
        if (changeFilter) {
          this.filter = null
          this.$refs.condition.reset()
        }
      }
    },
    // 删除 sheet
    onDelPane (targetKey) {
      const delID = this.panesArr.filter(pane => pane.key === targetKey)[0].id

      this.confirm(() => {
        this.$http.post('/zg-autoflow/autoFlow/sub/del', [delID], (data) => {
          this.$message.success('删除成功')
          this.promiseAll(this.param)
        })
      }, '确定要删除该子流程吗？')
    },
     onCondition (param) {
      const form = JSON.parse(param)
      form.flowId = this.flowId
      this.$http.post('/zg-autoflow/autoFlow/step/page', form, data => {
        this.list = data.records.map(t => {
          t.key = t.id
          return t
        })
      })
    },
    search () {
      // this.$refs.page.search()
    },
    searchProcess () {
      this.promiseAll(this.param)
    },
    toAdd () {
       // 新增
      this.$refs.add.open(this.flowId)
    },
    toAddProcess () {
      this.$refs.AddProcess.open(this.list, this.processObj.processCode)
    },
    onSearch (data) {
      const diyHeaders = localStorage.getItem(this.currentUser.username + '_' + this.uniqueName)
      if (diyHeaders) {
        this.mergeHeader(JSON.parse(diyHeaders))
      }
      this.list = data.records.map(t => {
          t.key = t.id
          return t
      })
    },

    // 获取页签
    getTabs (data) {
      const tabs = data.map((t, i) => {
        t.key = (i + 1) + ''
        t.title = t.name
        t.inputValue = [
          {
            label: '条件一',
            value: t.field,
            key: 'field'
          },
          {
            label: '条件一值',
            value: t.fieldValue,
            key: 'fieldValue'
          },
          {
            label: '条件二',
            value: t.field2,
            key: 'field2'
          },
          {
            label: '条件二值',
            value: t.field2Value,
            key: 'field2Value'
          }
        ]
        return t
      })
      this.panesArr = [...this.panes, ...tabs]
    },
    promiseAll (param) {
      param.flowId = this.flowId
      const searchPromise = this.$http.post('/zg-autoflow/autoFlow/step/page', param)
      const getTabsPromise = this.$http.post('/zg-autoflow/autoFlow/sub/all', { flowCode: param.obj.code })

      Promise.all([searchPromise, getTabsPromise])
        .then(results => {
          const searchResult = results[0].data
          const getTabsResult = results[1].data
          this.onSearch(searchResult)
          this.getTabs(getTabsResult)
        })
        .catch(error => {
          // 任何一个请求失败
          console.error(error)
        })
    },
    open (param) {
      this.param = param
      this.processObj.processName = param.obj.name
      this.processObj.processCode = param.obj.code
      this.flowId = param.obj.id
      this.activeKey = '-1'
      this.visible = true
      this.promiseAll(param)
    }

  }
}
</script>

<style lang="scss" scoped>

</style>
